<?php

namespace app\index\controller;

use addons\thirdwork\library\Application;
use app\admin\model\Payslip;
use app\admin\model\PayslipFeedback;
use app\admin\model\PayslipLogs;
use app\admin\model\PayslipSend;
use app\admin\model\UserDepartment;
use app\common\controller\Frontend;
use fast\Tree;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Config;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Validate;

class Manage extends Frontend
{
	protected $layout      = 'manage';
	protected $noNeedRight = ['*'];

	public function _initialize()
	{
		parent::_initialize();
		$auth = $this->auth;
		$this->assign('auth', $this->auth);
		if ($this->request->isMobile()) {
			$this->error(__('请使用企业微信桌面端'), '/');
		}

		if ($this->auth->group_id != 2) {
			$this->error(__('您没有权限访问管理端'), '/');
		}

		if (!Config::get('fastadmin.usercenter')) {
			$this->error(__('User center already closed'), '/');
		}

		//监听注册登录退出的事件
		Hook::add('user_login_successed', function ($user) use ($auth) {
			$expire = input('post.keeplogin') ? 30 * 86400 : 0;
			Cookie::set('uid', $user->id, $expire);
			Cookie::set('token', $auth->getToken(), $expire);
		});
		Hook::add('user_register_successed', function ($user) use ($auth) {
			Cookie::set('uid', $user->id);
			Cookie::set('token', $auth->getToken());
		});
		Hook::add('user_delete_successed', function ($user) use ($auth) {
			Cookie::delete('uid');
			Cookie::delete('token');
		});
		Hook::add('user_logout_successed', function ($user) use ($auth) {
			Cookie::delete('uid');
			Cookie::delete('token');
		});
	}

	/**
	 * 会员中心
	 */
	public function index()
	{
		$years = [];
		for ($i = date('Y'); $i >= 2022; $i --) {
			$years[] = $i;
		}
		$last_month = date('Y-m', strtotime('midnight first day of -1 month'));
		$data       = [
			'years'           => $years,
			'user_count'      => (new \app\common\model\User)->where(['status' => 'normal'])->count(),
			'success_count'   => (new PayslipLogs)->where(['status' => 2])->count(),
			'error_count'     => (new PayslipLogs)->where(['status' => 3])->count(),
			'money_total'     => (new PayslipLogs)->where(['status' => ['>', 0]])->sum('payslip_total'),
			'money_lastmonth' => (new PayslipLogs)->where(['status' => ['>', 0], 'month' => $last_month])->sum('payslip_total'),
		];
		$this->assign($data);
		return $this->view->fetch();
	}

	public function charts()
	{
		$year = $this->request->param('year', date('Y'), 'intval');
		$type = $this->request->param('type');
		for ($i = $year . '01'; $i <= $year . '12'; $i ++) {
			$month          = date('Y-m', strtotime($i . '01'));
			$data['year'][] = $month;
			if ($type == 'ygsl') {
				$data['data'][] = PayslipLogs::where(['month' => $month, 'user_id' => ['>', 0]])->group('user_id')->count();
			} else {
				$data['data'][] = PayslipLogs::where(['month' => $month, 'user_id' => ['>', 0]])->sum('payslip_total');
			}
		}
		$this->success('success', NULL, $data);
	}

	/**
	 * 发薪类型设置
	 */
	public function payslip_type()
	{
		if ($this->request->isPost()) {
			$payslip_type = $this->request->post('row.payslip_type', '', 'trim');
			if (empty($payslip_type)) {
				$this->error('请至少添加一个类型');
			}
			\app\common\model\Config::where('name', 'payslip_type')->update(['value' => $payslip_type]);
			\app\common\model\Config::refreshFile(TRUE);
			$this->success('保存成功');
		}
	}

	/**
	 * 新增工资条
	 */
	public function payslip_add()
	{
		$payslip_type = config('site.payslip_type');
		if ($this->request->isPost()) {

			$params = $this->request->post('row/a', [], 'trim');
			if (empty($params['payslip_type']) || empty($params['month']) || empty($params['file'])) {
				$this->error('参数错误');
			}

			$payslip_config = config('site.payslip_config');
			if ($payslip_config['open_auto_title'] == 1) { //自动拼接
				$payslipType = array2select($payslip_type);
				if (empty($payslipType[$params['payslip_type']])) {
					$this->error('错误的类型');
				}
				$title = date('Y年m月', strtotime($params['month'])) . $payslipType[$params['payslip_type']]; //2022年12月基本工资
			} else {
				$title = $payslip_config['title'];
			}

			$payslipLogs = $this->payslipHandle($params['file']);
			if (!$payslipLogs) {
				$this->error(__('请在工资表中至少添加一行数据'));
			}
			$error_json                   = [];
			$statistics['import_success'] = 0; //导入成功数
			$statistics['import_error']   = 0; //导入失败数
			$statistics['batch_success']  = 0; //匹配成功数
			$statistics['batch_error']    = 0; //匹配失败数
			Db::startTrans();
			try {
				$data       = [
					'title'        => $title,
					'manage_id'    => $this->auth->id,
					'payslip_type' => $params['payslip_type'],
					'payslip_file' => $params['file'],
					'year'         => date('Y', strtotime($params['month'])),
					'month'        => $params['month'],
					'status'       => 0
				];
				$payslip    = Payslip::create($data);
				$payslip_id = $payslip->id;
				foreach ($payslipLogs as $log) {
					if ($log['user_id']) { //是否已匹配到员工，如果匹配到，检查是否已经存在同月的发放记录
						$check = (new PayslipLogs)->where(['user_id' => $log['user_id'], 'payslip_type' => $data['payslip_type'], 'month' => $data['month']])->count();
						if ($check) {
							$error_json[] = $log['nickname'] . ' ' .$title;
							$statistics['import_error'] ++;
							continue;
						}
					}
					$log['payslip_id']   = $payslip_id;
					$log['payslip_type'] = $data['payslip_type'];
					$log['payslip_json'] = empty($log['payslip_json']) ? [] : json_encode($log['payslip_json'], JSON_UNESCAPED_UNICODE);
					$log['month']        = $data['month'];
					$statistics['import_success'] ++;
					if ($log['user_id']) {
						$statistics['batch_success'] ++;
					} else {
						$statistics['batch_error'] ++;
					}
					PayslipLogs::create($log, TRUE);
				}
				if ($error_json) {
					$payslip->error_json = json_encode($error_json, JSON_UNESCAPED_UNICODE);
					$payslip->save();
				}
				Db::commit();
			} catch (\Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}

			$this->success('导入已完成', NULL, [
				'next_url'   => url('manage/payslip_check', ['id' => $payslip_id]),
				'error_json' => $error_json,
				'statistics' => $statistics
			]);
		}

		$this->assign('payslip_type', $payslip_type);
		$this->assign('payslip_type_json', json_encode($payslip_type, JSON_UNESCAPED_UNICODE));
		return $this->view->fetch();
	}

	/**
	 * 核对工资表
	 */
	public function payslip_check()
	{
		if ($this->request->isPost()) {
			$id      = $this->request->post('id', '0', 'intval');
			$ids     = $this->request->post('ids/a', [], 'trim');
			$type    = $this->request->post('type', 'change', 'trim');
			$user_id = $this->request->post('user_id', '0', 'intval');

			if ($type == 'user_search') { //用户搜索
				$nickname = $this->request->post('nickname', '', 'trim');
				if (empty($nickname)) {
					$this->error('请输入员工姓名');
				}
				$list = (new \app\common\model\User)->alias('u')
				                                    ->join('user_department ud', 'ud.id = u.department_id', 'LEFT')
				                                    ->whereLike('u.nickname', '%' . $nickname . '%')
				                                    ->field('u.id, u.avatar, u.nickname, ud.name AS `department_name`')
				                                    ->order('u.id DESC')
				                                    ->select();
				if (empty($list)) {
					$this->error('未查到员工信息');
				}
				$this->success('查询成功', NULL, ['data' => $list]);
			}

			if ($ids && $type == 'batch_remove') { //批量删除
				$ids = (new PayslipLogs)->where(['id' => ['in', $ids]])->column('id');
				if (empty($ids)) {
					$this->error('参数错误');
				}
				(new PayslipLogs)->where(['id' => ['in', $ids]])->delete();
				$this->success('删除成功');
			}

			$row = (new PayslipLogs)->where(['id' => $id])->find();
			if (empty($row)) {
				$this->error('参数错误');
			}
			if ($type == 'change') { //修改
				$row->payslip_total = $this->request->post('payslip_total', 0, 'floatval');
				$row->payslip_json  = json_encode($this->request->post('payslip_json/a', ''), JSON_UNESCAPED_UNICODE);
				$row->save();
				$this->success('保存成功');
			}
			if ($type == 'cancel') { //取消
				$row->user_id = 0;
				$row->save();
				$this->success('取消成功');
			}
			if ($type == 'remove') { //删除
				$row->delete();
				$this->success('删除成功');
			}
			if ($type == 'user_bind') { //用户匹配
				$check = (new PayslipLogs)->where(['user_id' => $user_id, 'payslip_type' => $row['payslip_type'], 'month' => $row['month']])->count();
				if ($check) {
					$this->error('用户已存在匹配记录，不能重复匹配');
				}
				$row->user_id = $user_id;
				$row->save();
				$this->success('匹配成功');
			}
		}

		$id            = $this->request->param('id', '0', 'intval');
		$department_id = $this->request->param('department_id', '0', 'intval');
		$keywords      = $this->request->param('keywords', '', 'trim');
		$status        = $this->request->param('status', '1', 'intval');
		$payslip       = (new Payslip)->where(['id' => $id])->find();
		if (empty($payslip)) {
			$this->error('参数错误');
		}
		if ($payslip['status'] > 0) {
			$this->error('当前工资表已经生成，无法再次设置', 'manage/payslip_add');
		}
		$where = ['p.payslip_id' => $id, 'p.user_id' => $status == 1 ? ['>', 0] : 0];
		if ($keywords) {
			$where['u.nickname|u.mobile'] = ['like', '%' . $keywords . '%'];
		}
		if ($department_id) {
			$where['u.department_id'] = ['in', $department_id];
		}
		$list    = (new PayslipLogs)->alias('p')
		                            ->join('user u', 'u.id = p.user_id', 'LEFT')
		                            ->join('user_department ud', 'ud.id = u.department_id', 'LEFT')
		                            ->where($where)
		                            ->field('p.id, p.user_id, p.payslip_total, p.payslip_json, u.username, u.nickname, ud.name AS `department_name`')
		                            ->order('p.user_id ASC')
		                            ->paginate(10);
		$lists   = $list->items();
		$columns = [];
		foreach ($lists as $key => &$item) {
			$payslip_json = json_decode($item['payslip_json'], TRUE);
			if ($payslip_json) {
				foreach ($payslip_json as $name => $value) {
					if ($key == 0) {
						$columns[] = $name;
					}
					$item[$name] = $value;
				}
			}
		}
		$depList = collection((array) (new UserDepartment)->order('weigh', 'desc')->select())->toArray();
		Tree::instance()->init($depList);
		$this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
		$departments    = [];
		foreach ($this->rulelist as &$v) {
			$departments[$v['id']] = $v['name'];
		}

		$this->assign('id', $id);
		$this->assign('columns', $columns);
		$this->assign('departments', $departments);
		$this->assign('lists', $list->jsonSerialize());
		$this->assign('department_id', $department_id);
		$this->assign('keywords', $keywords);
		$this->assign('status', $status);
		return $this->view->fetch();
	}

	/**
	 * 发放工资表
	 */
	public function payslip_confirm()
	{
		$id      = $this->request->param('id', '0', 'intval');
		$payslip = (new Payslip)->where(['id' => $id])->find();
		if (empty($payslip)) {
			$this->error('参数错误');
		}
		if ($payslip['status'] > 0) {
			$this->error('当前工资表已经生成，无法再次设置', 'manage/payslip_add');
		}
		if ($this->request->isPost()) {
			$time   = $this->request->param('time', '', 'trim');
			$status = $this->request->param('status', '0', 'intval');
			if (!in_array($status, [1, 2])) {
				$this->error('参数错误');
			}
			$estimatetime = time();
			if ($status == 2) {
				if (empty($time)) {
					$this->error('请选择定时发送时间');
				}
				$estimatetime = strtotime($time);
				if ($estimatetime <= time()) {
					$this->error('定时发送时间必须大于当前时间');
				}
			}
			$payslip->status       = $status;
			$payslip->estimatetime = $estimatetime;
			$payslip->save();
			(new PayslipLogs)->update(['estimatetime' => $estimatetime], ['payslip_id' => $payslip['id']]);
			$this->success('设置成功', 'manage/payslip_list');
		}
		$this->assign('payslip', $payslip);
		$this->assign('payslip_config', config('site.payslip_config'));
		return $this->view->fetch();
	}

	/**
	 * 下载模板
	 */
	public function payslip_template()
	{
		$title = ['姓名', '账号', '实发金额'];
		$data  = [];
		$list  = \app\common\model\User::where(['status' => 'normal'])->field('id, username, nickname')->select();
		if ($list) {
			foreach ($list as $item) {
				$data[] = [$item['nickname'], $item['username'], ''];
			}
		}
		export($title, $data);
	}

	/**
	 * 发送记录
	 */
	public function payslip_list()
	{
		$year         = $this->request->get('year', date('Y'), 'trim');
		$type         = $this->request->get('type', '', 'trim');
		$payslip_type = config('site.payslip_type');
		$where        = [];
		if ($year) {
			$where['year'] = $year;
		}
		if ($type) {
			$where['payslip_type'] = $type;
		}
		$list  = (new Payslip)->where($where)
		                      ->field('id, title, status, estimatetime, sendtime')
		                      ->order('id ASC')
		                      ->paginate(12);
		$lists = $list->items();
		foreach ($lists as &$item) {
			$item['user_count'] = (new PayslipLogs)->where(['payslip_id' => $item['id'], 'user_id' => ['>', 0]])->count();
		}
		$this->assign('year', $year);
		$this->assign('type', $type);
		$this->assign('lists', $list->jsonSerialize());
		$this->assign('payslip_type', $payslip_type);
		return $this->view->fetch();
	}

	/**
	 * 工资详情
	 */
	public function payslip_detail()
	{
		$id       = $this->request->param('id', '0', 'intval');
		$keywords = $this->request->param('keywords', '', 'trim');
		$status   = $this->request->param('status', '0', 'intval');
		$payslip  = (new Payslip)->where(['id' => $id])->find();
		if (empty($payslip)) {
			$this->error('参数错误');
		}

		if ($this->request->isPost()) {
			$logs_id = $this->request->param('logs_id', '0', 'intval');
			$data    = (new PayslipLogs)->where(['id' => $logs_id, 'payslip_id' => $payslip['id'], 'user_id' => ['>', 0]])->find();
			if (empty($data)) {
				$this->error('记录不存在');
			}
			$data['list'] = select2array(json_decode($data['payslip_json'], TRUE), 'value', 'name');
			$this->success('', NULL, ['data' => $data]);
		}

		$where = ['p.payslip_id' => $id, 'p.user_id' => ['>', 0]];
		if ($keywords) {
			$where['u.nickname|u.mobile'] = ['like', '%' . $keywords . '%'];
		}
		if ($status) {
			$where['p.status'] = $status;
		}
		$list = (new PayslipLogs)->alias('p')
		                         ->join('user u', 'u.id = p.user_id', 'LEFT')
		                         ->join('user_department ud', 'ud.id = u.department_id', 'LEFT')
		                         ->where($where)
		                         ->field('p.id, p.user_id, p.is_view, p.status, p.sendtime, u.username, u.nickname, u.position, u.mobile, ud.name AS `department_name`')
		                         ->order('p.user_id ASC')
		                         ->paginate(12);

		$statistics_1 = (new PayslipLogs)->where(['payslip_id' => $payslip['id'], 'user_id' => ['>', 0], 'status' => 2])->count(); //已发
		$statistics_2 = (new PayslipLogs)->where(['payslip_id' => $payslip['id'], 'user_id' => ['>', 0], 'status' => ['in', '1,3']])->count(); //未发
		$statistics_3 = (new PayslipLogs)->where(['payslip_id' => $payslip['id'], 'user_id' => ['>', 0], 'is_view' => 1])->count(); //已读
		$statistics_4 = (new PayslipLogs)->where(['payslip_id' => $payslip['id'], 'user_id' => ['>', 0], 'is_feedback' => 1])->count(); //已反
		$payslip_type = config('site.payslip_type');

		$this->assign('lists', $list->jsonSerialize());
		$this->assign('keywords', $keywords);
		$this->assign('status', $status);
		$this->assign('payslip', $payslip);
		$this->assign('statistics_1', $statistics_1);
		$this->assign('statistics_2', $statistics_2);
		$this->assign('statistics_3', $statistics_3);
		$this->assign('statistics_4', $statistics_4);
		$this->assign('payslip_type', array2select($payslip_type));
		return $this->view->fetch();
	}

	/**
	 * 工资更新
	 */
	public function payslip_save()
	{
		if ($this->request->isPost()) {
			$id  = $this->request->post('id', '0', 'intval');
			$row = (new PayslipLogs)->where(['id' => $id])->find();
			if (empty($row)) {
				$this->error('参数错误');
			}
			$row->payslip_total = $this->request->post('payslip_total', 0, 'floatval');
			$row->payslip_json  = json_encode($this->request->post('payslip_json/a', ''), JSON_UNESCAPED_UNICODE);
			$row->save();
			$this->success('保存成功');
		}
	}

	/**
	 * 工资单个重发
	 */
	public function payslip_send()
	{
		if ($this->request->isPost()) {
			$logs_id = $this->request->param('logs_id', '0', 'intval');
			$row     = (new PayslipLogs)->where(['id' => $logs_id])->find();
			if (empty($row)) {
				$this->error('未查到工资表记录');
			}
			$config = config('site.payslip_config');
			$title  = (new Payslip)->where(['id' => $row['payslip_id']])->value('title');
			$userid = (new \app\common\model\User())->where(['id' => $row['user_id']])->value('username');
			if (empty($title)) {
				$this->error('未查到工资表');
			}
			if (empty($userid)) {
				$this->error('未查到用户ID');
			}
			$app  = new Application(get_addon_config('thirdwork'));
			$data = [
				[
					'title'       => $title, //标题，不超过128个字节，超过会自动截断
					'description' => $config['zhaiyao'], //描述，不超过512个字节，超过会自动截断
					'url'         => url('/index/index/index', ['first' => 'yes'], TRUE, TRUE), //点击后跳转的链接。
					'picurl'      => cdnurl($config['image'], TRUE), //图文消息的图片链接，最长2048字节，支持JPG、PNG格式，较好的效果为大图 1068*455，小图150*150。
				]
			];
			$res  = $app->wechatwork->sendNewsMessage($data, $userid);

			//记录发送日志
			$logs = [
				'user_ids'  => $userid,
				'request'   => $res['request'],
				'response'  => $res['response'],
				'status'    => $res['code'] ? 1 : 2,
				'manage_id' => $this->auth->id
			];
			PayslipSend::create($logs);

			if ($res['code'] == 1) {
				$row->status   = 2;
				$row->sendtime = time();
				$row->save();
				$this->success('通知已发送');
			} else {
				$row->status   = 3;
				$row->sendtime = time();
				$row->save();
				$this->error($res['msg']);
			}
		}
	}

	/**
	 * 工资导出
	 */
	public function payslip_export()
	{
		$id       = $this->request->param('id', '0', 'intval');
		$keywords = $this->request->param('keywords', '', 'trim');
		$status   = $this->request->param('status', '0', 'intval');
		$payslip  = (new Payslip)->where(['id' => $id])->find();
		if (empty($payslip)) {
			$this->error('参数错误');
		}
		$where = ['p.payslip_id' => $id, 'p.user_id' => ['>', 0]];
		if ($keywords) {
			$where['u.nickname|u.mobile'] = ['like', '%' . $keywords . '%'];
		}
		if ($status) {
			$where['p.status'] = $status;
		}
		$title = ['姓名', '部门', '职位', '账号', '手机号码', '发送时间', '状态'];
		$data  = [];
		$list  = (new PayslipLogs)->alias('p')
		                          ->join('user u', 'u.id = p.user_id', 'LEFT')
		                          ->join('user_department ud', 'ud.id = u.department_id', 'LEFT')
		                          ->where($where)
		                          ->field('p.id, p.user_id, p.status, p.sendtime, u.username, u.nickname, u.position, u.mobile, ud.name AS `department_name`')
		                          ->order('p.user_id ASC')
		                          ->select();
		if ($list) {
			foreach ($list as $item) {
				$data[] = [$item['nickname'], $item['department_name'], $item['position'], $item['username'], $item['mobile'], $item['sendtime_text'], $item['status_text']];
			}
		}
		export($title, $data, $payslip['title']);
	}

	/**
	 * 工资全部重发
	 */
	public function payslip_resend()
	{
		if ($this->request->isPost()) {
			$id  = $this->request->post('id', '0', 'intval');
			$row = (new Payslip)->where(['id' => $id])->find();
			if (empty($row)) {
				$this->error('参数错误');
			}
			$row->status       = 1;
			$row->estimatetime = time();
			$row->save();
			(new PayslipLogs)->update(['status' => 1], ['payslip_id' => $id]);
			$this->success('发送任务已创建，请稍后查看结果。');
		}
	}

	/**
	 * 反馈查看
	 */
	public function payslip_feedback()
	{
		$status   = $this->request->param('status', '0', 'intval');
		$keywords = $this->request->param('keywords', '', 'trim');
		$where    = [];
		if ($keywords) {
			$where['u.nickname|u.mobile'] = ['like', '%' . $keywords . '%'];
		}
		if ($status) {
			$where['p.status'] = $status;
		}
		$list = (new PayslipFeedback)->alias('p')
		                             ->join('user u', 'u.id = p.user_id', 'LEFT')
		                             ->join('user_department ud', 'ud.id = u.department_id', 'LEFT')
		                             ->where($where)
		                             ->field('p.id, p.user_id, p.status, p.month, p.content_json, u.username, u.nickname, u.position, u.mobile, ud.name AS `department_name`')
		                             ->order('p.id DESC')
		                             ->paginate(12);
		if ($list) {
			foreach ($list as $key => &$item) {
				$content_json    = json_decode($item['content_json'], TRUE);
				$content_json    = array_pop($content_json);
				$item['content'] = $content_json['question'] ?? '-';
			}
		}
		$data = [
			'status'   => $status,
			'keywords' => $keywords,
			'lists'    => $list->jsonSerialize()
		];
		$this->assign($data);
		return $this->view->fetch();
	}

	/**
	 * 反馈详情
	 */
	public function payslip_feedback_detail()
	{
		if ($this->request->isPost()) {
			$id   = $this->request->post('id', 0, 'intval');
			$data = (new PayslipFeedback)->alias('p')
			                             ->join('user u', 'u.id = p.user_id', 'LEFT')
			                             ->join('user_department ud', 'ud.id = u.department_id', 'LEFT')
			                             ->where(['p.id' => $id])
			                             ->field('p.id, p.status, p.content_json, u.avatar, u.nickname, ud.name AS `department_name`')
			                             ->find();
			if (empty($data)) {
				$this->error('参数错误');
			}
			$data['content'] = json_decode($data['content_json'], TRUE);
			$this->success('success', NULL, ['data' => $data]);
		}
	}

	/**
	 * 反馈处理
	 */
	public function payslip_feedback_save()
	{
		if ($this->request->isPost()) {
			$id      = $this->request->post('id', 0, 'intval');
			$content = $this->request->post('content/a');
			$data    = (new PayslipFeedback)->where(['id' => $id])->find();
			if (empty($data) || empty($content)) {
				$this->error('参数错误');
			}
			$username     = $data->user()->value('username');
			$content_json = $data['content_json'];
			foreach ($content as $key => $item) {
				$content_json = PayslipFeedback::feedback_log($content_json, $item, 'A', $key);
			}
			$data->content_json = $content_json;
			$data->status       = 2;
			$data->save();

			$work = new Application(get_addon_config('thirdwork'));
			$work->wechatwork->sendTextMessage('您的反馈管理员已回复，请进入工资条-我的反馈中查看', $username);

			$this->success('处理成功');
		}
	}

	/**
	 * 反馈删除
	 */
	public function payslip_feedback_remove()
	{
		if ($this->request->isPost()) {
			$id   = $this->request->post('id', 0, 'intval');
			$key  = $this->request->post('key', '', 'trim');
			$data = (new PayslipFeedback)->where(['id' => $id])->find();
			if (empty($data) || $key == '') {
				$this->error('参数错误');
			}
			$content_json = json_decode($data['content_json'], TRUE);
			if (empty($content_json[$key])) {
				$this->error('记录不存在');
			}
			unset($content_json[$key]);
			$data->content_json = json_encode(array_values($content_json), JSON_UNESCAPED_UNICODE);
			$data->save();
			$this->success('删除成功');
		}

	}

	/**
	 * 发放设置
	 */
	public function payslip_settings()
	{
		$payslip_config = config('site.payslip_config');
		if ($this->request->isPost()) {
			$params = $this->request->post('row/a', [], 'trim');
			\app\common\model\Config::where('name', 'payslip_config')->update(['value' => json_encode($params, JSON_UNESCAPED_UNICODE)]);
			\app\common\model\Config::refreshFile(TRUE);
			$this->success('保存成功');
		}
		$default_title           = date('Y') . '年' . date('m') . '月基本工资';
		$payslip_config['title'] = $payslip_config['open_auto_title'] == 1 ? $default_title : $payslip_config['title'];
		$this->assign('payslip_config', $payslip_config);
		$this->assignconfig('default_title', $default_title);
		return $this->view->fetch();
	}

	/**
	 * 通讯录
	 */
	public function address_book()
	{
		if ($this->request->isPost()) {
			$department_id = $this->request->param('department_id', '0', 'trim');
			$nickname      = $this->request->param('nickname', '', 'trim');
			$status        = $this->request->param('status', '', 'trim');
			$where         = [];
            $status        = 'normal';
			if ($status) {
				$where['u.status'] = $status;
			}
			if ($nickname) {
				$where['u.nickname'] = ['like', '%' . $nickname . '%'];
			}
			if ($department_id) {
				$where['u.department_id'] = ['in', $department_id];
			}
			$list = (new \app\common\model\User)->alias('u')
			                                    ->join('user_department ud', 'ud.id = u.department_id', 'LEFT')
			                                    ->where($where)
			                                    ->field('u.id, u.avatar, u.username, u.nickname, u.position, u.status, u.group_id, u.mobile, ud.name AS `department_name`')
			                                    ->order('u.group_id DESC, u.id ASC')
			                                    ->paginate(10);
			$this->success('success', NULL, $list);
		}

		$userCount  = (new \app\common\model\User)->where(['status' => 'normal'])->count();
		$groupArray = (new UserDepartment)->where(['status' => 'normal'])->order('weigh DESC')->select();
		foreach ($groupArray as $v) {
			$groupList[] = [
				'id'     => $v['id'],
				'parent' => $v['pid'] ?: '#',
				'text'   => $v['name'],
				'type'   => 'group',
				'state'  => ['opened' => TRUE]
			]; //jstree opened 展开前两级
		}
		$this->assignconfig('groupList', $groupList);
		$this->view->assign('userCount', $userCount);
		return $this->view->fetch();
	}

	/**
	 * 通讯录同步
	 */
	public function address_sync()
	{
		UserDepartment::syncData();
		\app\admin\model\User::syncData();
		$this->success('已同步');
	}

	/**
	 * 管理员设置
	 */
	public function switch_group()
	{
		if ($this->request->isPost()) {
			$id    = $this->request->param('id', '0', 'intval');
			$value = $this->request->param('value', '0', 'intval');
			if ($id && $value) {
				\app\common\model\User::update(['group_id' => $value], ['id' => $id]);
				$this->success('操作成功');
			}
			$this->error('参数错误');
		}
	}

	/**
	 * 重置手势密码
	 */
	public function clear_pwd()
	{
		if ($this->request->isPost()) {
			$id   = $this->request->post('id');
			$user = \app\common\model\User::get($id);
			if (empty($user)) {
				$this->error('用户不存在');
			}
			$user->querypwd = '';
			$user->save();
			$this->success('密码已重置');
		}
	}

	/**
	 * 重置密码
	 */
	public function changepwd()
	{
		if ($this->request->isPost()) {
			$uid           = $this->request->post('uid');
			$newpassword   = $this->request->post('newpassword');
			$renewpassword = $this->request->post('renewpassword');
			$rule          = [
				'newpassword'   => 'require|regex:\S{6,30}',
				'renewpassword' => 'require|regex:\S{6,30}|confirm:newpassword',
				'__token__'     => 'token',
			];
			$msg           = [
				'renewpassword.confirm' => __('Password and confirm password don\'t match')
			];
			$data          = [
				'newpassword'   => $newpassword,
				'renewpassword' => $renewpassword
			];
			$field         = [
				'newpassword'   => __('New password'),
				'renewpassword' => __('Renew password')
			];
			$validate      = new Validate($rule, $msg, $field);
			$result        = $validate->check($data);
			if (!$result) {
				$this->error(__($validate->getError()));
			}
			$user = \app\common\model\User::get($uid);
			if (empty($user)) {
				$this->error('用户不存在');
			}
			$user->querypwd = md5(md5($newpassword));
			$user->save();
			$this->success(__('Reset password successful'));
		}
	}

	protected function payslipHandle($file)
	{
		$filePath = ROOT_PATH . DS . 'public' . DS . $file;
		if (!is_file($filePath)) {
			$this->error(__('No results were found'));
		}
		//实例化reader
		$ext = pathinfo($filePath, PATHINFO_EXTENSION);
		if (!in_array($ext, ['xlsx'])) {
			$this->error(__('Unknown data format'));
		}
		$reader = new Xlsx();
		//加载文件
		$insert = [];
		try {
			if (!$PHPExcel = $reader->load($filePath)) {
				exception(__('Unknown data format'));
			}
			$currentSheet    = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
			$allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
			$allRow          = $currentSheet->getHighestRow(); //取得一共有多少行
			$maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
			$fields          = [];
			for ($currentRow = 1; $currentRow <= 1; $currentRow ++) {
				for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn ++) {
					$val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
					$fields[] = $val;
				}
			}
			$default_fields = ['姓名', '账号', '实发金额'];
			if (count($default_fields) != count(array_intersect($default_fields, $fields))) {
				exception('您上传的文件数据格式不正确');
			}
			for ($currentRow = 2; $currentRow <= $allRow; $currentRow ++) {
				$values = [];
				for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn ++) {
					$val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
					$values[] = is_null($val) ? '' : $val;
				}
				$row  = [];
				$temp = array_combine($fields, $values);
				foreach ($temp as $k => $v) {
					$value = trim($v);
					switch ($k) {
						case '姓名':
							$row['nickname']  = trim($v);
							$row['manage_id'] = $this->auth->id;
							$row['status']    = 1;
							break;
						case '账号':
							$row['user_id'] = \app\common\model\User::where(['username' => trim($v)])->value('id', 0);
							break;
						case '实发金额':
							$row['payslip_total'] = $value;
							break;
						default:
							if (trim($k)) {
								$row['payslip_json'][$k] = $v;
							}
					}
				}
				$insert[] = $row;
			}
		} catch (\Exception $exception) {
			$this->error($exception->getMessage());
		}
		return $insert;
	}

}
